<?php

/**
 * @author kevin
 * @date 2016-01-16 14:00:00
 * @desc 用户登录管理
 */

if (!defined('IN_ECS'))
{
    die('Hacking attempt');
}
$version = '1.0';   //版本号

if ($_POST['api_version'] != $version)      //网店的接口版本低
{
	api_err('0x008', 'a low version api');
}
if(empty($_POST['st'])){
	api_err('0x008', 'param st is Missing');
}
//微信登录授权
if($_POST['st'] == 'wxpre'){ 
	require_once (ROOT_PATH."includes/tenpayapp/WxPayPubHelper/WxPay.pub.config.php");
    $data = array(
        'appid' => WxPayConf_pub::APPID,
        'scope' => 'snsapi_userinfo',
        'state' => rand(1000,9999).rand(1000,9999),
    );
	data_back($data, '', RETURN_TYPE);  //返回数据
}
//微信登录
if($_POST['st'] == 'wxlogin'){
    $code = trim($_POST['code']);
    if(empty($code)){
        api_err('0x008', 'code can not empty');
    }
	require_once (ROOT_PATH."includes/tenpayapp/WxPayPubHelper/WxPay.pub.config.php");
    //获取token
    $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code';
    $url = sprintf($url, WxPayConf_pub::APPID, WxPayConf_pub::APPSECRET,$code);
    $result = curlFunc($url);
    if(isset($result['errcode'])){
        api_err('0x008', 'access token get failed');
    }
    //获取用户信息
    $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN';
    $url = sprintf($url, $result['access_token'], $result['openid']);
    $result = curlFunc($url);
    if(isset($result['errcode'])){
        api_err('0x008', 'userInfo get failed');
    }
    $other = array(
        'head_img'  => $result['headimgurl'],
        'alias'     => $result['nickname'],
        'sex'       => $result['sex'],
    );
	$data = checkThreeUserInfo($result['openid'], 1,$other);
	data_back($data, '', RETURN_TYPE);  //返回数据
}
//支付宝登录授权
if($_POST['st'] == 'zfbpre'){
    include_once(ROOT_PATH.'includes/alipayapp/alipay.config.php');
    include_once(ROOT_PATH.'includes/alipayapp/lib/alipay_core.function.php');
    include_once(ROOT_PATH.'includes/alipayapp/lib/alipay_rsa.function.php');
    $data = array(
        'apiname'   => 'com.alipay.account.auth',
        'app_id'    => $alipay_config['app_id'],
        'app_name'  => 'mc',
        'auth_type' => 'AUTHACCOUNT',
        'biz_type'  => 'openservice',
        'method'    => 'alipay.open.auth.sdk.code.get',
        'pid'       => $alipay_config['partner'],
        'product_id'=> 'APP_FAST_LOGIN',
        'scope'     => 'kuaijie',
        'sign_type' => 'RSA',
        'target_id' => md5(uniqid()),
    );
    $prestr = '';
    foreach($data as $k=>$v){
        $prestr .= $k.'='.$v.'&';
    }
    $prestr = trim($prestr, '&');
    $data['sign'] = urlencode(rsaSign($prestr, $alipay_config['private_key_path']));
    $prestr = '';
    foreach($data as $k=>$v){
        $prestr .= $k.'='.$v.'&';
    }
    $prestr = trim($prestr, '&');
    $data['prestr'] = $prestr;//createLinkstring($data);
	data_back($data, '', RETURN_TYPE);  //返回数据
}
//支付宝登录
if($_POST['st'] == 'zfblogin'){
    $auth_code = trim($_POST['code']);
    if(empty($auth_code)){
        api_err('0x008', 'code can not empty');
    }
    try{
        include_once(ROOT_PATH.'includes/alipayapp/alipay.config.php');
        include_once(ROOT_PATH.'includes/aliaop/request/AlipayUserUserinfoShareRequest.php');
        include_once(ROOT_PATH.'includes/aliaop/request/AlipaySystemOauthTokenRequest.php');
        include_once(ROOT_PATH.'includes/aliaop/AopClient.php');
        include_once(ROOT_PATH.'includes/aliaop/AopEncrypt.php');
        include_once(ROOT_PATH.'includes/aliaop/SignData.php');
        $url = 'https://openapi.alipay.com/gateway.do';
        $aop = new AopClient ();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = $alipay_config['app_id'];
        $aop->rsaPrivateKeyFilePath = $alipay_config['private_key_path'];
        $aop->alipayPublicKey=$alipay_config['ali_public_app_path'];
        $aop->apiVersion = '1.0';
        $aop->postCharset='utf-8';
        $aop->format='json';
        //获取token
        $request = new AlipaySystemOauthTokenRequest ();
        $request->setGrantType("authorization_code");
        $request->setCode($auth_code);
        $result = $aop->execute( $request );
        $token = $result->alipay_system_oauth_token_response;
        //获取用户信息
        $request = new AlipayUserUserinfoShareRequest ();
        $result = $aop->execute ( $request, $token->access_token);
        $userInfo = $result->alipay_user_userinfo_share_response;
        if(empty($result) || empty($userInfo) || isset($userInfo->code)){
            api_err('0x008', 'userInfo get failed');
        }
        $other = array(
            'head_img'  => $userInfo->avatar,
            'alias'     => $userInfo->nick_name,
            'sex'       => ($userInfo->gender == 'F' || $userInfo->gender == 'f')?2:1,
        );
	    $data = checkThreeUserInfo($userInfo->user_id, 2,$other);
	    data_back($data, '', RETURN_TYPE);  //返回数据
    }catch(Exception $e){ 
        api_err('0x008', $e->getMessage());
    }
}
//用户注册
if($_POST['st'] == 'register'){
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
    $confirm = trim($_POST['confirm']);
    $captcha = trim($_POST['captcha']);
    $type = 0;
    if(empty($username) || empty($password) || empty($confirm) || empty($captcha)){
        api_err('0x008', 'param username/password/confirm/captcha can not empty');
    }
    if(!preg_match("/^[0-9 a-z A-Z]{6,20}$/", $username)){
        api_err('0x008', '账号名称为6-20个字母/数字/下划线');
    }
    $len = strlen($password);
    if($len < 6 || $len > 20){
        api_err('0x008', '密码为6-20个任意字符');
    }
    if($password != $confirm){
        api_err('0x008', '俩次输入的密码不一致');
    }
    include_once(ROOT_PATH . 'includes/cls_captcha.php');
    /* 检查验证码是否正确 */
    $validator = new captcha();
    if (!$validator->check_word($captcha)){
        api_err('0x008', '验证码无效');
    }
    $sql = "SELECT * FROM " .$GLOBALS['ecs']->table('users'). " WHERE user_name = '$username' and type='{$type}' LIMIT 0, 1";
    $userInfo = $GLOBALS['db']->getRow($sql);
    if(!empty($userInfo)){
        api_err('0x008', '用户已存在');
    }
	$data = checkThreeUserInfo($username, $type, $_POST);
	data_back($data, '', RETURN_TYPE);  //返回数据
}
//用户登录
if($_POST['st'] == 'login'){
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
    $type = 0;
    if(empty($username) || empty($password)){
        api_err('0x008', 'param useranme/password can not empty');
    }
    $sql = "SELECT * FROM " .$GLOBALS['ecs']->table('users'). " WHERE user_name = '$username' and type='{$type}' LIMIT 0, 1";
    $userInfo = $GLOBALS['db']->getRow($sql);
    if(empty($userInfo)){
        api_err('0x008', '用户不存在');
    }
    if($userInfo['password'] != md5(md5($_POST['password']).$userInfo['ec_salt'])){
        api_err('0x008','密码不正确');
    }
	$data = checkThreeUserInfo($username,$type,$_POST);
	data_back($data, '', RETURN_TYPE);  //返回数据
}
//用户ID检测
if(!isset($GLOBALS['uid'])){
	api_err('0x015', 'You have not logged on');
}
$user_id = $GLOBALS['uid'];
//获取会员信息
if($_POST['st'] == 'profile'){
	$data = get_profile($user_id);
	$data['order_statistics'] = order_statistics($user_id);
}
//头像上传
if($_POST['st'] == 'upload'){
	include_once(ROOT_PATH . 'includes/cls_image.php');
	$image = new cls_image($_CFG['bgcolor']);
	if ((isset($_FILES['head_img']['error']) && $_FILES['head_img']['error'] == 0) || (!isset($_FILES['head_img']['error']) && isset($_FILES['head_img']['tmp_name'] ) &&$_FILES['head_img']['tmp_name'] != 'none'))
	{
		$head_img = $image->upload_image($_FILES['head_img'], 'upload/File');
        if(empty($head_img)){
            api_err('0x008','image moved fail');
        }
		$profile = array(
			'user_id'=>$user_id,
            'other'=>array(
			            'head_img'=>$head_img
                    )
		);
		if(!edit_profile($profile)){
			api_err('0x008','Head image update fail');
		}
		$data['head_img'] = get_image_pathv1('', $head_img);
	}else{
		api_err('0x008','Upload image fail');
	}
}
//
/*if($_POST['st'] == 'check'){
    $token = $_POST['token'];
    if(empty($token)){
        api_err('0x008', 'param st is Missing');
    }
    include_once('includes/lib_passport.php');
    $data = checkTokenToUid($token);
}*/
//st参数错误
if(!isset($data)){
	api_err('0x008');
}
data_back($data, '', RETURN_TYPE);  //返回数据
function curlFunc($url){
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_HEADER,0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    $res = curl_exec($ch);
    curl_close($ch);
    $json_obj = json_decode($res,true);
    return $json_obj;
}
function curlPost($url, array $params = array()){
    $ch = curl_init ();
    curl_setopt ( $ch, CURLOPT_URL, $url );
    curl_setopt ( $ch, CURLOPT_POST, 1 );
    curl_setopt ( $ch, CURLOPT_HEADER, 0 );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $params );
    $return = curl_exec ( $ch );
    curl_close ( $ch );var_dump($url, $params,$return);exit;
    $return = json_decode($return, true);
    return $return;
}
